package com.fangyi.yunmusic.service.es;

import com.fangyi.yunmusic.pojo.es.UserDocument;
import com.fangyi.yunmusic.repository.es.UserRepository;
import org.elasticsearch.common.lucene.search.function.FiltersFunctionScoreQuery;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.WeightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;

@Service
public class UserSearchService {

    @Autowired
    private UserRepository userRepository;


    public Page<UserDocument> queryUser(Integer pageNum, Integer pageSize, String query) {

        // 设置查询条件
        FunctionScoreQueryBuilder.FilterFunctionBuilder[] functions = {
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(matchPhraseQuery("nickname", query), new WeightBuilder().setWeight(90)), // 设置权重
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(matchPhraseQuery("description", query), new WeightBuilder().setWeight(10)) // 设置权重
        };
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(functions)
                .scoreMode(FiltersFunctionScoreQuery.ScoreMode.SUM)     // 设置权重分求和模式
                .setMinScore(10);   // 设置权重分最低分


        Pageable pageable = PageRequest.of(pageNum, pageSize);// 设置分页

        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(functionScoreQueryBuilder).build();

        return userRepository.search(nativeSearchQuery);


    }


}
